<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row>
          <el-button type="danger" @click="handleDeleteAll">批量删除</el-button>
          <el-button type="success" @click="handleAdd"
          >&emsp;新增&emsp;
          </el-button>
          <el-form :inline="true" :model="listQuery" class="demo-form-inline">
            <el-form-item label="显示状态">
              <el-select
                v-model="listQuery.status"
                clearable
                placeholder="请选择显示状态"
              >
                <el-option
                  v-for="item in status_options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="挂件名称">
              <el-input
                v-model="listQuery.name"
                clearable
                placeholder="请输入挂件名称"
              ></el-input>
            </el-form-item>
            <el-button type="primary" @click="getList">查询</el-button>
          </el-form>
        </el-row>
      </div>
      <div>
        <el-table
          ref="dataList"
          :data="menuList"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          border
          row-key="id"
          style="margin-bottom: 20px;"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection"></el-table-column>
          <el-table-column label="序号" prop="id"></el-table-column>
          <el-table-column label="挂件名称" prop="name"></el-table-column>
          <el-table-column label="状态" prop="status">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status" type="success">显示</el-tag>
              <el-tag v-else type="danger">隐藏</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="上线时间" prop="start_time"></el-table-column>
          <el-table-column label="关闭时间" prop="end_time">
            <template slot-scope="scope">
              <p v-if="scope.row.end_time">{{ scope.row.end_time }}</p>
              <p v-else>永久</p>
            </template>
          </el-table-column>
          <el-table-column label="挂件图标" prop="picture">
            <template slot-scope="scope">
              <el-popover max-width="420" placement="right" trigger="hover">
                <img :src="scope.row.picture" alt="" style="max-width: 200px"/>
                <img
                  slot="reference"
                  :src="scope.row.picture"
                  alt=""
                  style="width: 50px"
                />
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="操作类型" prop="type_text"></el-table-column>
          <el-table-column label="链接" prop="url"></el-table-column>
          <el-table-column label="排序" prop="sort"></el-table-column>
          <el-table-column label="展示位" prop="position"></el-table-column>
          <el-table-column label="时间段" prop="time_slot_text">
            <template slot-scope="scope">
              <p v-html="scope.row.time_slot_text"></p>
            </template>
          </el-table-column>
          <el-table-column label="房间类型" prop="allow_room_type_text">
            <template slot-scope="scope">
              <p v-if="scope.row.allow_room_type_text">
                {{ scope.row.allow_room_type_text }}
              </p>
              <p v-else>所有房间类型</p>
            </template>
          </el-table-column>
          <el-table-column label="显示等级" prop="allow_rank">
            <template slot-scope="scope">
              <p v-if="scope.row.allow_rank">{{ scope.row.allow_rank }}</p>
              <p v-else>所有等级</p>
            </template>
          </el-table-column>
          <el-table-column label="可见用户" prop="allow_user">
            <template slot-scope="scope">
              <p v-if="scope.row.allow_user">{{ scope.row.allow_user }}</p>
              <p v-else>所有用户</p>
            </template>
          </el-table-column>
          <el-table-column label="可见房间" prop="allow_room">
            <template slot-scope="scope">
              <p v-if="scope.row.allow_room">{{ scope.row.allow_room }}</p>
              <p v-else>所有房间</p>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="190px">
            <template slot-scope="scope">
              <el-button
                icon="el-icon-edit"
                plain
                size="mini"
                type="primary"
                @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                icon="el-icon-delete"
                plain
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 删除弹框 -->
    <el-dialog
      :visible.sync="deleteDialogVisible"
      title="确定删除吗?"
      width="435px"
    >
      <span style=""
      ><em style="font-style:normal;color:red">删除后不可恢复</em
      >，你还要继续吗？</span
      >
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDelete">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 新增编辑弹框 -->
    <el-dialog
      v-dialogDrag
      :title="titleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="700px"
      @close="handleDialogClose('editRulesForm')"
    >
      <el-form
        ref="editRulesForm"
        :model="editRulesForm"
        :rules="editRulesFormRules"
        class="demo-ruleForm"
        label-width="120px"
      >
        <el-form-item label="挂件名称" prop="name">
          <el-input
            v-model="editRulesForm.name"
            placeholder="请输入挂件名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio v-model="editRulesForm.status" :label="1">显示</el-radio>
          <el-radio v-model="editRulesForm.status" :label="0">隐藏</el-radio>
        </el-form-item>
        <el-form-item label="上线时间" prop="start_time">
          <el-date-picker
            v-model="editRulesForm.start_time"
            placeholder="选择上线时间"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="关闭时间">
          <el-date-picker
            v-model="editRulesForm.end_time"
            clearable
            placeholder="不选择则默认为拥有有效"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="图标" prop="picture">
          <el-upload
            :http-request="customizeUpload"
            :on-success="handleAvatarSuccess"
            :show-file-list="false"
            action=""
            class="avatar-uploader"
          >
            <img
              v-if="editRulesForm.picture"
              :src="editRulesForm.picture"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select v-model="editRulesForm.type" placeholder="操作类型">
            <el-option
              v-for="item in type_options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="editRulesForm.type === 3" label="链接">
          <el-input
            v-model="editRulesForm.url"
            placeholder="请输入外部链接"
          ></el-input>
        </el-form-item>
        <el-form-item label="位置">
          <el-radio v-model="editRulesForm.position" :label="1">1</el-radio>
          <el-radio v-model="editRulesForm.position" :label="2">2</el-radio>
          <el-radio v-model="editRulesForm.position" :label="3">3</el-radio>
        </el-form-item>
        <el-form-item label="排序">
          <el-input
            v-model="editRulesForm.sort"
            placeholder="请输入排序(默认为0)"
          ></el-input>
        </el-form-item>
        <el-form-item label="房间类型">
          <el-select
            v-model="editRulesForm.allow_room_type"
            clearable
            multiple
            placeholder="不选则为全部类型"
          >
            <el-option
              v-for="item in room_options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="可见等级">
          <el-input
            v-model="editRulesForm.allow_rank"
            placeholder="不输入则默认为0"
          ></el-input>
        </el-form-item>
        <el-form-item label="可见用户">
          <el-input
            v-model="editRulesForm.allow_user"
            placeholder="不输入则全部用户均可见"
          ></el-input>
        </el-form-item>
        <el-form-item label="可见房间">
          <el-input
            v-model="editRulesForm.allow_room"
            placeholder="不输入则全部房间均可见"
          ></el-input>
        </el-form-item>
        <el-form-item label="时间段">
          <div
            v-for="(item, index) in time_arr"
            :key="'时间段' + index"
            class="mb-3"
          >
            <el-input-number
              v-model="item.first"
              :max="parseInt(item.last)"
              :min="0"
            ></el-input-number>
            至
            <el-input-number
              v-model="item.last"
              :max="24"
              :min="parseInt(item.first)"
            ></el-input-number>
            <el-button v-if="index" @click.prevent="removeDomain(item)"
            >删除
            </el-button
            >
          </div>
          <el-button @click="addDomain">新增时间段</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogFormVisible = false">返回</el-button>
          <el-button type="primary" @click="submitForm('editRulesForm')"
          >提交
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { deleteData, listData, postData, postUpdateData, roomType } from '@/api/room/roomPendant'

export default {
  name: 'Pendant',
  data() {
    return {

      listQuery: {
        status: undefined,
        name: undefined
      },
      status_options: [
        { value: 1, label: '显示' },
        { value: 0, label: '隐藏' }
      ],
      type_options: [
        { value: 1, label: '小猫钓鱼' },
        { value: 2, label: '球球大作战' },
        { value: 3, label: '跳转链接' },
        { value: 4, label: 'boss大作战' },
        { value: 6, label: '幸运树游戏' },
        { value: 7, label: '抢糖果游戏' },
        { value: 10, label: '航海纪元' }

      ],
      room_options: [],
      menuList: [],
      multipleSelection: [],
      dataIds: undefined,
      deleteDialogVisible: false,
      editRulesForm: {
        id: undefined,
        name: undefined,
        status: 0,
        start_time: undefined,
        end_time: undefined,
        picture: undefined,
        type: 3,
        url: undefined,
        position: 1,
        sort: undefined,
        allow_user: undefined,
        allow_room: undefined,
        allow_room_type: undefined,
        allow_rank: undefined,
        time_slot: undefined
      },
      editRulesFormRules: {
        // name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        // picture: [{ required: true, message: "请上传图片", trigger: "change" }]
        // start_time: [
        //   { required: true, message: "请选择上线时间", trigger: "change" }
        // ]
      },
      time_arr: [{ first: 0, last: 24 }],
      dialogFormVisible: false,
      dialogStatus: 'create',
      // dialog的头部信息
      titleMap: {
        update: '编辑',
        create: '添加'
      }
    }
  },
  created() {
    this.getList()
    this.handleGetRoomType()
  },
  methods: {
    getList() {
      let data = {}
      for (let key in this.listQuery) {
        if (
          this.listQuery[key] !== undefined &&
          this.listQuery[key] !== null &&
          this.listQuery[key] !== ''
        ) {
          data[key] = this.listQuery[key]
        }
      }
      listData(data).then(res => {
        this.menuList = res.data
      })
    },
    handleGetRoomType() {
      roomType().then(res => {
        let arr = []
        for (let key in res.data) {
          arr.push({ value: parseInt(key), label: res.data[key] })
        }
        this.room_options = arr
      })
    },
    handleAdd() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleEdit(row) {
      this.dialogStatus = 'update'
      for (let key in this.editRulesForm) {
        if (key === 'allow_room_type') {
          if (row[key]) {
            this.editRulesForm[key] = row[key].split(',').map(item => {
              return parseInt(item)
            })
          } else {
            this.editRulesForm[key] = undefined
          }
        } else {
          if(key === 'time_slot'){
            this.time_arr[0].first = row[key].split('-')[0];
            this.time_arr[0].last = row[key].split('-')[1];
          }else{
          this.editRulesForm[key] = row[key]
          }
        }
      }

      this.dialogFormVisible = true
    },
    handleAvatarSuccess() {
      this.editRulesForm.picture = this.ossLastImgUrl
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let data = Object.assign({}, this.editRulesForm)
          if (data.allow_room_type && data.allow_room_type.length > 0) {
            data.allow_room_type = data.allow_room_type.join(',')
          } else {
            data.allow_room_type = undefined
          }
          let time_str = ''
          this.time_arr.forEach((item, index) => {
            if (index === 0) {
              time_str += `${item.first}-${item.last}`
            } else {
              time_str += `,${item.first}-${item.last}`
            }
          })
          data.time_slot = time_str

          if (this.dialogStatus === 'create') {
            postData(data).then(res => {
              if (res.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              }
            })
          } else {
            postUpdateData(data).then(res => {
              if (res.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              }
            })
          }
        } else {

          return false
        }
      })
    },

    // 勾选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 点击单个删除
    handleDelete(row) {
      this.dataIds = { id: `${row.id}` }
      this.deleteDialogVisible = true
    },
    // 点击批量删除
    handleDeleteAll() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请先勾选要删除的内容',
          type: 'warning'
        })
        return
      } else if (this.multipleSelection.length !== 0) {
        let ids = ''
        for (let key in this.multipleSelection) {
          ids += `${this.multipleSelection[key].id},`
        }
        ids = ids.substring(0, ids.length - 1)
        this.dataIds = { id: ids }
      }
      this.deleteDialogVisible = true
    },
    // 确定删除
    confirmDelete() {
      deleteData(this.dataIds).then(response => {
        if (response.code === 200) {
          this.getList()
          this.deleteDialogVisible = false
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          })
        } else {
        }
      })
    },
    handleDialogClose(formName) {
      this.editRulesForm = {
        id: undefined,
        name: undefined,
        status: 0,
        start_time: undefined,
        end_time: undefined,
        picture: undefined,
        type: 3,
        url: undefined,
        position: 1,
        sort: undefined,
        allow_user: undefined,
        allow_room: undefined,
        allow_room_type: undefined,
        allow_rank: undefined
      }
      this.$refs[formName].resetFields()
    },
    removeDomain(item) {
      let index = this.time_arr.indexOf(item)
      if (index !== -1) {
        this.time_arr.splice(index, 1)
      }
    },
    addDomain() {
      this.time_arr.push({
        first: 0,
        last: 24
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.demo-form-inline {
  float : right;

  .el-form-item {
    margin-bottom : 0;
  }
}

::v-deep.avatar-uploader .el-upload {
  border        : 1px dashed #d9d9d9;
  border-radius : 6px;
  cursor        : pointer;
  position      : relative;
  overflow      : hidden;
}

.avatar-uploader .el-upload:hover {
  border-color : #409eff;
}

.avatar-uploader-icon {
  font-size   : 28px;
  color       : #8c939d;
  width       : 100px;
  height      : 100px;
  line-height : 100px;
  text-align  : center;
}

.avatar {
  width   : 100px;
  height  : 100px;
  display : block;
}
</style>
